<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  NDatePicker,
  NSelect,
  useMessage,
  type FormItemRule,
  type FormInst,
  NModal
} from 'naive-ui'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import useRouteReplace from '@/hooks/useRouteReplace'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import useRouteParam from '@/hooks/useRouteParam'
import type { InterpreterModel } from '@/api/interpreter'
import validator from 'validator'
import VScope from '@/views/OA/Common/Scope.vue'
import dayjs from 'dayjs'
import { values } from 'lodash-es'

const route = useRoute()
const message = useMessage()
const routeReplace = useRouteReplace(route.query.redirect as string)
const interpreterId = route.params.id as string
const isUpdate = route.query.type === 'u'
useRouteParam('id', main)

const formInst = ref<FormInst | null>(null)
const formData = ref({} as InterpreterModel)
const addUser = ref<any>(null)
const scopeModalVisible = ref<boolean>(false)
const submitLoading = ref(false)
const handleSubmit = () => {
  formInst.value?.validate(async (error) => {
    if (error) return
    submitLoading.value = true

    try {
      const [error, res] = await sendRequest<HttpResponse>({
        module: 'interpreter',
        api: isUpdate ? 'update' : 'save',
        override: {
          data: isUpdate ? formData.value : {
            ...formData.value,
            identifyingId: addUser.value.fullId
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      window.flags.flushInterpreterTable = true
      routeReplace()
    } catch (error) {
      if (!(error instanceof Error)) return
      message.error(error.message)
    } finally {
      submitLoading.value = false
    }
  })
}
const handleChangeMember = (v: any) => {
  if(v && v.length > 0) {
    addUser.value = v[0]
    getUserInfo(v[0].identifyingId)
  }
  scopeModalVisible.value = false
}
/** 获取用户信息并赋值 */
const getUserInfo = async (userId: string) => {
  const [error, res] = await sendRequest<HttpResponse<any>>({
    module: 'user',
    api: 'detailInfo',
    uri: {
      id: userId
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  const { userName, phone, idNumber, sex, birthday } = res.data
  formData.value.interpreterName = userName
  formData.value.phoneNumber = phone
  formData.value.idNumber = idNumber
  formData.value.sex = sex
  birthday && (formData.value.birthday = dayjs(birthday).format('YYYY-MM-DD'))
  message.success("选择成功")
}
const getScopeDefaultList = () => {
  if(!isUpdate) return addUser.value ? [addUser.value] : []
  if(formData.value) {
    return [
      { fullId: formData.value.identifyingId, noticeCode: null, identifyingId: formData.value.identifyingId }
    ]
  }
}
// 获取详情
const queryInfo = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<InterpreterModel>>({
      module: 'interpreter',
      api: 'info',
      uri: {
        id: interpreterId
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    if (res.data?.birthday) {
      res.data.birthday = res.data.birthday.split(' ')[0]
    }
    formData.value = res.data || {}
  } catch (error) {
    console.error(error)
  }
}



onMounted(main)

function main() {
  if (isUpdate) queryInfo()
}

const limitRule = (len: number): FormItemRule => {
  return {
    trigger: ['blur', 'input'],
    message: `不能超过${len}字`,
    validator: (_, value) => (value ? value.length <= len : true)
  }
}
</script>

<template>
  <DetailFormProvider>
    <div class="interpreter-cur">
      <div class="ic-title">{{ isUpdate ? '编辑' : '新增' }}讲解员</div>

      <div class="ic-card">
        <NForm ref="formInst" :model="formData" label-placement="left" require-mark-placement="left"
          label-width="130px">
          <NFormItem label="选择人员：" path="member" show-require-mark>
            <NButton type="primary" @click="scopeModalVisible = true">{{ isUpdate ? '修改人员' : '选择人员' }}</NButton>
          </NFormItem>
          <NFormItem label="姓名：" path="interpreterName" :rule="[
            {
              required: true,
              message: '请输入姓名',
              trigger: ['blur', 'input']
            },
            limitRule(10)
          ]">
            <NInput disabled v-model:value="formData.interpreterName" placeholder="请输入" />
          </NFormItem>
          <NFormItem label="手机号：" path="phoneNumber" :rule="[
            {
              required: true,
              message: '请输入手机号',
              trigger: ['blur', 'input']
            },
            {
              message: '请输入正确的手机号',
              validator: (_, value) => (value ? validator.isMobilePhone(value, 'zh-CN') : true),
              trigger: ['blur', 'input']
            }
          ]">
            <NInput disabled v-model:value="formData.phoneNumber" placeholder="请输入" />
          </NFormItem>
          <NFormItem label="身份证号：" path="idNumber" :rule="[
            {
              required: true,
              message: '请输入身份证号',
              trigger: ['blur', 'input']
            },
            {
              message: '请输入正确的身份证号',
              validator: (_, value) =>
                value
                  ? /^[1-9][0-9]{5}(18|19|20)[0-9]{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])[0-9]{3}([0-9]|X)$/.test(
                    value
                  )
                  : true,
              trigger: ['blur', 'input']
            }
          ]">
            <NInput disabled v-model:value="formData.idNumber" placeholder="请输入" />
          </NFormItem>
          <NFormItem label="性别：" path="sex" :rule="{
            required: true,
            message: '请选择性别',
            trigger: ['blur', 'change'],
            type: 'number'
          }">
            <NSelect disabled v-model:value="formData.sex" :options="[
              { label: '女', value: 2 },
              { label: '男', value: 1 }
            ]" />
          </NFormItem>
          <NFormItem label="出生日期：" path="birthday">
            <NDatePicker disabled v-model:formatted-value="formData.birthday" format="yyyy-MM-dd" type="date" placeholder="请输入"
              style="flex: 1" />
          </NFormItem>
          <NFormItem label="现居住地：" path="residence" :rule="limitRule(50)">
            <NInput v-model:value="formData.residence" placeholder="请输入" />
          </NFormItem>
          <NFormItem label="级别：" path="level" :rule="{
            required: true,
            message: '请选择级别',
            trigger: ['blur', 'change']
          }">
            <NSelect v-model:value="formData.level" :options="[
              { label: '专职讲解员', value: 'A6601' },
              { label: '兼职讲解员', value: 'A6602' }
            ]" />
          </NFormItem>
          <NFormItem label="介绍：" path="introduce" :rule="limitRule(500)" class="n-form-item--textarea">
            <NInput v-model:value="formData.introduce" type="textarea" placeholder="请输入" rows="5" />
          </NFormItem>
        </NForm>
      </div>
    </div>
  </DetailFormProvider>
  <NModal :auto-focus="false" v-model:show="scopeModalVisible" @close="scopeModalVisible = false">
    <VScope @close="scopeModalVisible = false" @scopeSubmit="handleChangeMember" flat radioFlat :defaultList="getScopeDefaultList()"/>
  </NModal>
  <FixedAction>
    <div class="interpreter-cur-buttons">
      <NButton color="#999999" ghost :disabled="submitLoading" @click="routeReplace" style="width: 78px; height: 34px">
        取消
      </NButton>

      <NButton color="#5FB17F" :disabled="submitLoading" :loading="submitLoading" @click="handleSubmit"
        style="width: 78px; height: 34px">
        保存
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.interpreter-cur {
  min-height: 100%;
  padding: 16rem 16rem 110rem;

  .ic-card {
    padding: 20rem;
    background-color: #ebeceb;
  }

  .ic-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 22px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #5fb17f;
    margin-bottom: 10rem;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .n-form {
    display: flex;
    flex-direction: column;
    gap: 6rem 30rem;
    max-width: 360px;
    margin: 0 auto;
    translate: -30px 0;
  }

  .n-form-item--textarea {
    grid-column: 1 / -1;
  }

  :deep(.n-scrollbar-container) {
    overscroll-behavior-y: contain;
  }
}

.interpreter-cur-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}

.contacts {
  display: flex;
  flex-direction: column;
  gap: 10rem 0;

  .n-button {
    max-width: 126rem;
  }

  .contacts-content {
    display: grid;
    grid-template-columns: repeat(5, auto);
    gap: 10rem;
    padding: 15rem;
    background-color: #fff;
  }
}

.transfers-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10rem;

  .transfers {
    display: flex;
    align-items: center;
    gap: 10rem;

    .n-icon {
      cursor: pointer;
    }
  }
}
</style>
